
from flask import Flask, render_template
from flask_socketio import SocketIO, emit

app = Flask(__name__)
app.config['SECRET_KEY'] = 'mysecretkey'
socketio = SocketIO(app)

@app.route('/')
def index():
    return render_template('index.html')

@socketio.on('connect')
def handle_connect():
    print('Client connected')
    # 在这里可以发送一个初始消息给客户端
    emit('message', {'data': 'Welcome to the server push demo!'})

@socketio.on('request_data')
def handle_request_data():
    print('Data requested by client')
    # 模拟从数据库或其他数据源获取数据的过程
    data = {'title': 'Server Push Example', 'content': 'This is an example of server push in Flask-SocketIO.'}
    # 向客户端推送数据
    emit('data', data)

if __name__ == '__main__':
    socketio.run(app, port=5000)
    print('Server started')

